package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * OADDATA类
 * 实现对象属性描述符数据的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class OADDATA implements AxdrType {

    private byte[] dataCode = null;
    private OAD oad = null;
    private Data data = null;

    public OADDATA() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(OAD oad, Data data) {
        this.oad = oad;
        this.data = data;
    }

    public void setOAD(OAD oad) {
        this.oad = oad;
    }

    public void setData(Data data) {
        this.data = data;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        this.oad = new OAD();
        codeLength += this.oad.decode(input);

        this.data = new Data();
        codeLength += this.data.decode(input);

        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(this.dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            if (this.data != null && this.oad != null) {
                codeLength = 0;
                codeLength += this.data.encode(output);
                codeLength += this.oad.encode(output);
            } else {
                throw new RuntimeException("data or oad is null");
            }
        }

        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        try {
            this.encode(revOStream);
        } catch (RuntimeException e) {
            throw new RuntimeException("Error encoding OADDATA", e);
        }
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        if (this.oad != null && this.data != null) {
            return "sequence: {" + "oad: " + this.oad + ", data: " + this.data + "}";
        } else {
            return "oad || data is null";
        }
    }

    public OAD getOad() {
        return oad;
    }

    public Data getData() {
        return data;
    }
}